import os
import os.path

from dbManager import DbManager

home = os.path.expanduser('~')
if '.musicplayer' not in os.listdir(home):
    os.mkdir(os.path.join(home, '.musicplayer'))
dbPath = os.path.join(home, '.musicplayer', 'userData.db')
createTableString = """
CREATE TABLE IF NOT EXISTS playhistory(
    id INTEGER PRIMARY KEY autoincrement,
    name TEXT,
    author TEXT,
    playTimes INTEGER default 1    
)"""


class UserDbManager(DbManager):
    def __init__(self, database=dbPath, *args):
        super().__init__(database, *args)
        self.initDb()

    def initDb(self):
        self.createTable(createTableString)

    def getSongByPlayTimes(self, maxes=5) -> list:
        fetchedData = self.cursor.execute("""SELECT id FROM playhistory 
            ORDER BY playTimes DESC 
            LIMIT {}""".format(maxes))
        return [i[0] for i in fetchedData]

    def addPlayTimesById(self, songId, name='Test', author='Test'):
        try:
            insertData = self.cursor.execute("""INSERT INTO playhistory 
                (id, name, author) VALUES 
                ({0}, '{1}', '{2}')
                """.format(songId, name, author))
        except:
            updateData = self.cursor.execute("""UPDATE playhistory 
                SET playTimes = playTimes + 1
                WHERE id = {}
                """.format(songId))
        self.db.commit()


if __name__ == '__main__':
    userDb = UserDbManager()
    userDb.cursor.execute("""SELECT * from playhistory""")
    print(userDb.cursor.fetchall())
    for i in userDb.cursor.fetchall():
        print(i)
